<template>
  <div class="con">
    <div class="contbox6_10">
      <div class="titlelist6_10">活动管理 / 排名奖励</div>
      <div class="content">
        <div class="relus">
          活动配置说明：根据活动POS交易量进行排名奖励活动
          <img @click="relues" src="../../assets/images/sm.png" />
        </div>
        <div class="jibenInfo">基本信息</div>
        <div class="listGroup">
          <div class="lister">
            <div class="listName">活动名称</div>
            <el-input
              :disabled="disNo == 'true'"
              @focus="selectInstitution"
              v-model="form.activeName"
              maxlength="30"
              style="width: 300px; margin-right: 40px"
            ></el-input>
          </div>

          <div class="lister">
            <div class="listName">活动品牌</div>

            <el-select
              :disabled="diss"
              v-model="form.Brand"
              @change="pinChange"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="item in optionsBrand"
                :key="item.uid"
                :label="item.channelName"
                :value="item.uid"
              ></el-option>
            </el-select>
          </div>
          <div class="lister">
            <div class="listName">活动商品</div>
            <el-select
              multiple
              @change="
                xingType(form.BrandTypeNum);
                $forceUpdate();
              "
              v-model="form.BrandTypeNum"
              value-key="productName"
              style="width: 200px"
              placeholder="请选择"
              collapse-tags
            >
              <el-option
                label="全选"
                value="全选"
                @click.native="selectAll"
                :disabled="diss"
              ></el-option>
              <el-option
                :disabled="diss"
                v-for="item in optionsBrandTypeNum"
                :key="item.productUid"
                :label="item.productName"
                :value="item.productUid"
              ></el-option>
            </el-select>
          </div>
          <div class="lister">
            <div class="listName">考核时间</div>
            <div class="block">
              <el-date-picker
                :disabled="disNo == 'true'"
                class="timers"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                @input="daterangeChange"
                v-model="form.timers"
                :picker-options="pickerOptions"
                style="width: 200px"
                type="daterange"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束"
              ></el-date-picker>
            </div>
          </div>
          <div class="lister">
            <div class="listName">奖励发放时间</div>
            <div class="block">
              <el-date-picker
                :disabled="disNo == 'true'"
                value-format="yyyy-MM-dd"
                v-model="form.rewordDate"
                type="date"
                style="width: 300px !important"
                placeholder="选择日期"
              ></el-date-picker>
            </div>
          </div>
        </div>
        <div class="jibenInfo">规则(最多可达20名)</div>
        <div class="reward">
          <div class="listers">
            <div class="listNames">POS最低交易金额达到</div>
            <el-input
              onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              maxlength="9"
              :disabled="disNo == 'true'"
              @input="$forceUpdate()"
              v-model="form.totalAmt"
              placeholder=""
              style="margin-right: 10px"
            ></el-input
            >元可入排行榜，入榜后按照排名进行奖励。
          </div>
          <!-- <div class="left"></div>
      <div class="right"></div>-->
          <ul class="addLister">
            <el-button class="add" type="primary" @click="addRanking"
              >添加奖励名次</el-button
            >
            <li v-for="(item, index) in form.activeBrandOfficeTop" :key="index">
              <span class="nums">第{{ item.level }}名奖励</span>
              <el-input
              @input="value=>{item.rewardAmt=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')}"
                :disabled="disNo == 'true'"
                v-model="item.rewardAmt"
                maxlength="9"
                style="width: 160px; margin-right: 10px"
              />元
              <span
                @click="del(index)"
                v-if="index == form.activeBrandOfficeTop.length - 1"
                class="delete"
              >
                <img src="../../assets/images/del.png" alt />
              </span>
            </li>
          </ul>
        </div>
        <div class="foot">
          <el-button type="primary" @click="submit">下一步</el-button>
          <el-button @click="result">取消</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      title="规则说明"
      :visible.sync="dialogVisible3"
      width="800px"
      :before-close="handleClose"
    >
      <el-row>
        <el-form label-width="100px">
          <el-form-item label="活动说明：">1、POS交易量进行排名奖励活动，交易量目前只针对POS类交易做统计，活动只对选定品牌的商品进行交易统计。<br/>2、奖励排名最多可设置20名，最少设置1名，按照交易量多少进行排名奖励。<br/>3、排名次序根据交易额实时变动，排名次序统计到活动时间的最后一秒，活动结束后不在统计排名。</el-form-item>
          <el-form-item label="考核时间：">考核时间是活动总时间;普通代理参与活动有效期起止时间。</el-form-item>
          <el-form-item label="奖励规则：">已入榜的普通代理，活动结束后排名次序符合排名奖励规则，则获取奖励金额。</el-form-item>
          <el-form-item label="奖励方式：">统一结算，指定日期入账</el-form-item>
        </el-form>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible3 = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Littlehow } from "../../assets/js/util";
import axios from "axios";
import { date } from "../../assets/js/commion";
import https from "../../plugins/https";
export default {
  data() {
    return {
      diss: false,
      dialogVisible3: false,
      objectType: [
        { label: "个人", value: "0" },
        { label: "团队", value: "1" },
      ],
      options: [],
       // 时间选择
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() //如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      user: '',
      disNo: false,
      disNos: false,
      shows: false,
      tj: "2020-03-05 - 2020-06-23",
      rewordDate: null, //奖励发放时间
      userId: "",
      startDate: null,
      endDate: null,
      //选择品牌的id
      brandId: null,
      //提交的数据
      form: {
        activeUid: "", //活动的id
        activeName: "", //活动的名称
        startDate: "", //活动开始时间
        endDate: "", //活动结束时间
        rewordDate: "", //奖励发放时间
        productNoList: [],
        objectType: "",
        officeUids: [],
        totalAmt: "", //活动期间内最低交易总额
        // activeDesc: "", //活动描述
        // activeType: "", //活动类型
        // level: null, //排名层级
        rewardAmt: "", //奖励金额
        // productNoList: [], //两个id
        activeBrandOfficeTop: [{ level: "1", rewardAmt: "" }],

        // mechanism: "", //
        timers: [],
        // timers2: "",
        Brand: "",
        BrandType: "",
        BrandTypeNum: [], //活动商品
        // spType: "", //商品型号
        // minimum: "",
      },
      value1: "",
      value2: "",
      //参与活动品牌
      optionsBrand: null,
      Brand: "",
      // 品牌类型
      optionsBrandType: null,
      // BrandType:""
      BrandType: "",
      //   商品型号‘
      optionsBrandTypeNum: null,
      BrandTypeNum: [],
      minimum: "", //入帮交易最低限额
      num: 2,
      rewardGroup: [{ level: "1", rewardAmt: "" }],
      pinpaiId: null,
      xinghaoId: null,
      uid: null,
    };
  },
  activated() {
    this.num=2
    this.diss=false
    this.user=this.$route.query.user
    this.disNo = this.$route.query.isSshow;
    if (this.$route.query.bools) {
      this.form = {
        activeUid: "", //活动的id
        activeName: "", //活动的名称
        startDate: "", //活动开始时间
        endDate: "", //活动结束时间
        rewordDate: "", //奖励发放时间
        productNoList: [],
        objectType: "",
        officeUids: [],
        totalAmt: "", //活动期间内最低交易总额
        rewardAmt: "", //奖励金额
        // productNoList: [], //两个id
        activeBrandOfficeTop: [{ level: "1", rewardAmt: "" }],
        timers: [],
        Brand: "",
        BrandType: "",
        BrandTypeNum: [], //活动商品
      };
    }
    let uid = this.$route.query.uid;

    // console.log(uid);
    // 回显
    if (uid) {
      this.diss = true;
      https
        .queryUpdateActive({ activeUid: uid })
        .then((res) => {
          console.log("成功xxxxxx");
          console.log(res);
          this.form = res.data.data;
          // this.form.timers = [];
          this.form.BrandTypeNum = [];
          this.form.Brand = res.data.data.productNoList[0].channelUid;

          var arr = [];
          arr.push(res.data.data.startDate);
          arr.push(res.data.data.endDate);
          this.$set(this.form, "timers", arr);
          this.pinChange(this.form.Brand);
          this.form.totalAmt = res.data.data.activeBrandOfficeTop[0].totalAmt;

          this.num = res.data.data.activeBrandOfficeTop.length + 1;
          // alert(this.num)
          this.form.productNoList.channelUid = this.form.Brand;
          https
            .activeBrand({ brandChannelId: this.form.Brand })
            .then((res1) => {
              // alert(JSON.stringify(res1))
              this.optionsBrandTypeNum = res1.data.data;
              console.log(this.optionsBrandTypeNum);
              var temps = [];
              //拿到数组里面的来进行赋值操作
              for (let i = 0; i < res.data.data.productNoList.length; i++) {
                // temps.push()
                temps.push(res.data.data.productNoList[i].productUid);
              }
              this.form.BrandTypeNum = temps;
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      this.form.objectType = "0";
    }
    // alert(typeof this.disNo)
  },
  created() {
    // alert("这里执行")
    this.num=2
    this.user = this.$route.query.user;
    // alert(date.isDuringDate('2018/09/17', '2019/09/17'));
    var oemUid = localStorage.getItem("uid");
    axios
      .get("/api/office/getAllOfficeList")
      .then((res) => {
        console.log(res.data.data);
        console.log("这里");

        let datas = res.data.data;
        datas.map((item) => {
          item.label = item.name;
          item.value = item.uid;
        });
        //
        var format = {
          id: "uid", //菜单编号，作为树形查找id
          root: "", //顶层节点的parentId是root
          pid: "parentUid", //父节点标识字段为parentId
          child: "children", //构造出的树形子节点数组名为children
          sort: { field: "sortNo", direct: 1 },
        }; //排序字段为sortNo，且正序
        console.log(Littlehow.tree.format(datas, format));
        console.log();
        var result = Littlehow.tree.format(datas, format);
        this.options = result;
        console.log(this.options);
      })
      .catch((err) => {
        // alert("洒进来的咖啡机啦");
      });
    https
      .queryChannelNameList({ oemUid: oemUid })
      .then((res) => {
        console.log("品品牌");
        console.log(res.data.data);
        this.optionsBrand = res.data.data;
      })
      .catch((err) => {
        console.log(err);
      });

    this.queryList();
    // alert(this.disNo)
    // console.log(this.$route.query.isSshow, this.$route.query.shows);

    // this.disNo = this.$route.query.isSshow;

    this.disNo = this.$route.query.isSshow;
    // alert(this.disNo)
    this.disNos = this.$route.query.gai;
    // this.shows = this.$route.query.shows;
    this.userId = this.$route.query.uid;
    console.log(this.$route.query.uid);
    let uid = this.$route.query.uid;

    // console.log(uid);
    // alert(uid);
    // 回显
    if (uid) {
      https
        .queryUpdateActive({ activeUid: uid })
        .then((res) => {
          console.log("成功xxxxxx");
          console.log(res);
          this.form = res.data.data;
          // this.form.timers = [];
          this.form.BrandTypeNum = [];
          this.form.Brand = res.data.data.productNoList[0].channelUid;
          // this.form.timers.push(res.data.data.startDate);
          // this.form.timers.push(res.data.data.endDate);

          var arr = [];
          arr.push(res.data.data.startDate);
          arr.push(res.data.data.endDate);
          this.$set(this.form, "timers", arr);
          this.pinChange(this.form.Brand);
          this.form.totalAmt = res.data.data.activeBrandOfficeTop[0].totalAmt;

          this.num = res.data.data.activeBrandOfficeTop.length + 1;
          // alert(this.num)
          this.form.productNoList.channelUid = this.form.Brand;
          https
            .activeBrand({
              brandChannelId: this.form.Brand,
            })
            .then((res1) => {
              this.optionsBrandTypeNum = res1.data.data;
              console.log(this.optionsBrandTypeNum);
              var temps = [];
              //拿到数组里面的来进行赋值操作
              for (let i = 0; i < res.data.data.productNoList.length; i++) {
                // temps.push()
                temps.push(res.data.data.productNoList[i].productUid);
              }
              this.form.BrandTypeNum = temps;
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      this.form.objectType = "0";
    }
  },
  methods: {
    relues() {
      this.dialogVisible3 = true;
    },
    // 全选
    selectAll() {
    
      this.form.BrandTypeNum = [];
      if (this.form.BrandTypeNum.length < this.optionsBrandTypeNum.length) {
        if (this.diss != true) {
          // alert("多选执行")
          var allOption = [];
          for (var i = 0; i < this.optionsBrandTypeNum.length; i++) {
            allOption.push(this.optionsBrandTypeNum[i].productUid);
          }
          this.$set(this.form, "BrandTypeNum", allOption);
          console.log("下面是全选以后后端需要的数据");
          console.log(this.form.BrandTypeNum);
          this.xingType(this.form.BrandTypeNum);
          this.$forceUpdate();
        }
      } else {
        // alert("取消多选执行")
        var allOption = [];
        this.$set(this.form, "BrandTypeNum", allOption);
        this.xingType(this.form.BrandTypeNum);
        this.$forceUpdate();
      }
    },

    daterangeChange(e) {
      let _this = this;
      console.log(e);
      _this.$nextTick(() => {
        _this.$set(_this.form, "timers", [e[0], e[1]]);
        _this.$forceUpdate();
      });
      this.form.startDate = e[0];
      this.form.endDate = e[1];
    },

    shijian(val) {
      console.log(val);
      this.form.startDate = val[0];
      this.form.endDate = val[1];
    },
    delTag() {
      return false;
    },
    // 查询活动品牌
    queryList() {
      https
        .activeBrand({})
        .then((res) => {
          console.log("获取活动成果");
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    result() {
      this.$router.push({
        path: "activityManagement",
      });
    },

    addRanking() {
      if (this.form.activeBrandOfficeTop.length < 20) {
        var obj = { level: this.num, rewardAmt: "" };
        this.form.activeBrandOfficeTop.push(obj);
        this.num++;
        console.log(this.form.activeBrandOfficeTop);
      }
    },
    isDuringDate(beginDateStr, endDate) {
      var curDate = new Date(),
        beginDate = new Date(beginDateStr),
        endDate = new Date(endDate);
      if (this.form.rewordDate > this.form.endDate) {
        return false;
      } else {
        return true;
      }
    },
    warryInfo() {
      layer.open({
        content: "奖励发放时间大于统计结束时间",
        skin: "msg",
        time: 2,
      });
    },

    submit() {
      if (this.form.activeName == "")
        return layer.open({
          content: "活动名称不能未空",
          skin: "msg",
          time: 2,
        });
      if (this.form.Brand == "") {
        return layer.open({
          content: "活动品牌不能为空",
          skin: "msg",
          time: 2, //1秒后自动关闭
        });
      }
      if (this.form.productNoList.length == 0) {
        return layer.open({
          content: "活动商品不能为空",
          skin: "msg",
          time: 2, //1秒后自动关闭
        });
      }
      if (this.form.timers.length < 2)
        return layer.open({
          content: "考核时间不能为空",
          skin: "msg",
          time: 2,
        });
      if (this.form.rewardDate == "")
        return layer.open({
          content: "奖励发放时间不能为空",
          skin: "msg",
          time: 2,
        });
      
      console.log(this.form);
      //调用之前先清空上一次的数据
      this.$store.commit("clearSetActiveRanking");
      this.$store.commit("clearSetBannerData");
      this.$store.commit("clearSetBingImg");
      if (this.isDuringDate(this.form.endDate, this.form.rewordDate) != true) {
        //数据提交到vuex后面一起用
        this.$store.commit("setActiveRanking", this.form);
        console.log("查看是否未空");
        console.log(this);
        // return
        for(let b=0;b<this.form.activeBrandOfficeTop.length;b++){
        if(this.form.activeBrandOfficeTop[b].rewardAmt==""){
          layer.open({
            content: "排名奖励不能为空",
            skin: "msg",
            time: 2,
          });
         return false
        }else{
          this.$router.push({
          path: "nextActive",
          query: {
            uid: this.$route.query.uid,
            type: "/saveRankActive",
            user: this.user,
            name: "createActive",
          },
        });
        }
         
      }
        
      } else {
        return layer.open({
          content: "奖励发放时间要大于活动结束时间",
          skin: "msg",
          time: 2, //1秒后自动关闭
        });
        this.warryInfo();
      }
    },
    del(num) {
      if (this.$route.query.isSshow != true) {
        this.form.activeBrandOfficeTop.splice(num, 1);
        // console.log(num)
        this.num--;
      }
    },
    changeSel(val) {
      this.form.spType = val;
      this.pinpaiId = val; //品牌id
      console.log("发生改变");
      https
        .toChannelTypequeryProductList({
          channelType: val,
        })
        .then((res) => {
          alert(JSON.stringify(res));
          console.log(res);
          // alert(JSON.stringify(res))
          //活动商品
          this.optionsBrandTypeNum = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //请求品牌类型的接口
    pinChange(val) {
      console.log("id是");
      this.form.BrandTypeNum = [];
      console.log(val);
      //品牌id
      this.brandId = val;
      var ids = this.form.Brand;

      //根据品牌获取商品
      https
        .activeBrand({ brandChannelId: val })
        .then((res) => {
          console.log("这里");
          this.optionsBrandTypeNum = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    xingType(val) {
      const length = val.length;
      this.form.productNoList = [];
      console.log("下面是val");
      console.log(val);
      for (var i = 0; i < length; i++) {
        this.form.productNoList.push({
          channelUid: this.brandId,
          productUid: val[i],
        });
      }
      console.log("下面是用的那个");
      console.log(this.form.productNoList);
    },
  },
};
</script>

<style scoped>
.con {
  position: relative;
}
/deep/ .el-tag__close {
  display: none !important;
}
.wrap {
  width: 96%;
  margin: 0 auto;
}
.listGroup {
  display: flex;
  flex-wrap: wrap;
  /* padding-left: 60px; */
  box-sizing: border-box;
  float: left;
}
.maiLister {
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 30px;
  margin-top: 20px;
}
.lister {
  width: 450px;
  display: flex;
  justify-content: left;
  margin-bottom: 20px;
  align-items: center;
}
.listers {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: left;
  margin-bottom: 20px;
  align-items: center;
}
.listName {
  width: 90px;
  color: #909399;
  text-align: right;
  margin-right: 10px;
}
.listNames {
  width: 162px;
  color: #909399;
  text-align: right;
  margin-right: 10px;
}
.nums {
  display: inline-block;
  margin-right: 10px;
  color: #909399;
}
.mainTitle {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin: 20px 0;
  font-weight: 600;
}
.addLister {
  position: relative;
  display: flex;
  flex-wrap: wrap;
}
.addLister > li {
  margin-bottom: 20px;
  margin-left: 20px;
  width: 400px;
}
/deep/ .el-input__inner {
  width: 300px;
}
/deep/ .el-input {
  width: 300px;
}
/deep/ .el-popper {
  width: 300px;
}
/deep/ .addLister > li .el-input__inner {
  width: 160px !important;
}
.add {
  cursor: pointer;
  position: absolute;
  left: 770px;
  top: -62px;
}
.delete {
  cursor: pointer;
  left: 10px;
  position: relative;
}
/deep/ .timers .el-range-separator {
  width: 20px;
}
.topTitle {
  /* font-weight: bold; */
  font-size: 16px;
  margin-top: 40px;
  color: #2f2c29;
  margin-bottom: 20px;
  /* margin-bottom: 40px; */
}
.foot {
  margin-top: 50px;
  float: left;
  /* width: 100%; */
  margin-top: 50px;
  margin-left: 40%;
  margin-bottom: 20px;
}
/* 单独样式 */
.contbox6_10 {
  width: 100%;
  /* margin-left: 2%; */
  /*  height: 87.5vh; */
  overflow-x: auto;
  box-sizing: border-box;
  float: left;
}
.jibenInfo {
  width: calc(100% - 40px);
  margin: 0 20px 20px;
  height: 40px;
  line-height: 40px;
  float: left;
  font-size: 18px;
}
.relus {
  width: 100%;
  height: 30px;
  line-height: 30px;
  padding-left: 20px;
  background: #f9f4f7;
  /* color: #fb932b; */
}
</style>
